package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    //自动装配
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //在checkGroup添加表中添加数据
        checkGroupDao.add(checkGroup);
        //在映射表中返回添加数据的id
        //添加中间表数据
        setCheckgroupIdAndCheckitemIds(checkGroup.getId(),checkitemIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        //分页参数配置
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //查询
        Page<CheckGroup> page  = checkGroupDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public Integer[] findCheckitemIdsByCheckgroupId(Integer id) {
        return checkGroupDao.findCheckitemIdsByCheckgroupId(id);
    }

    @Override
    public void update(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.update(checkGroup);
        //删除中间表当前id的数据
        deleteCheckitemIdsByCheckGroupId(checkGroup.getId());
        //添加新的中间表该数据
        setCheckgroupIdAndCheckitemIds(checkGroup.getId(),checkitemIds);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    private void deleteCheckitemIdsByCheckGroupId(Integer checkGroupId) {
            checkGroupDao.deleteCheckitemIdByCheckGroupId(checkGroupId);
    }

    private void setCheckgroupIdAndCheckitemIds(Integer CheckgroupId, Integer[] checkitemIds) {
        //遍历
        for (Integer checkitemId : checkitemIds) {
            System.out.println(checkitemId);
            //封装进map中
            HashMap<String, Integer> map = new HashMap<>();
            map.put("CheckgroupId",CheckgroupId);
            map.put("checkitemId",checkitemId);
            checkGroupDao.setCheckgroupIdAndCheckitemId(map);
        }
    }
}
